package handler

import (
	"day116/cache"
	"day116/model"
	"day116/pkg"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	var user model.User
	redis_key := "user_err_" + username
	errorCount, _ := cache.Rdb.Get(cache.Ctx, redis_key).Int()
	if errorCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误3次，账号冻结中",
		})
		return
	}
	model.DB.Where("username = ?", username).Find(&user)
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "账号不存在",
		})
		return
	}
	if pkg.Md5(password) != user.Password {
		cache.Rdb.Incr(cache.Ctx, redis_key)
		if errorCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误3次，封禁2小时",
			})
			return
		}
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "登录成功",
		"user": user,
	})
	return
}
func AddUserRole(c *gin.Context) {
	uid, _ := strconv.Atoi(c.PostForm("uid"))
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	data := model.UserRole{
		Uid: uid,
		Rid: rid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func AddRoleNode(c *gin.Context) {
	rid, _ := strconv.Atoi(c.PostForm("rid"))
	nid, _ := strconv.Atoi(c.PostForm("nid"))
	data := model.RoleNode{
		Rid: rid,
		Nid: nid,
	}
	model.DB.Create(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}
func UserRoleList(c *gin.Context) {
	uid, _ := strconv.Atoi(c.Query("uid"))
	var data model.Role
	model.DB.Table("roles").Where("uid = ?", uid).Joins("left join user_roles on user_roles.rid = roles.id").Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
}
func RoleNodeList(c *gin.Context) {
	rid, _ := strconv.Atoi(c.Query("rid"))
	var data model.Node
	model.DB.Table("nodes").Where("rid = ?", rid).Joins("left join role_nodes on role_nodes.nid = nodes.id").Find(&data)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": data,
	})
}
